'''
Author: 红色梧桐 940120450@qq.com
Date: 2024-05-18 21:21:25
LastEditors: 红色梧桐 940120450@qq.com
LastEditTime: 2024-09-05 20:27:49
FilePath: \myReader\test.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from datetime import datetime
import json
from applications.models import Session
from applications.models.wx import WxMessage
from applications.extends.cacheUtils.redis import redis_client

message = redis_client.rpop("wechat_message")
if message:
    session = Session()
    try:
        data = json.loads(message.encode("utf-8"))
        message = data["message"]
        wx_id = data["wx_id"]
        create_time = data["create_time"] if 'create_time' in data else datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        msg = WxMessage(wx_id=wx_id, user=data["users"], message=message["content"], send_user=message["send"], create_time=create_time)
        session.add(msg)
        session.commit()
    except Exception as e:
        redis_client.lpush("wechat_message", message.encode("utf-8"))
        print("微信消息写入mysql任务异常", e)
        session.rollback()
    finally:
        session.close()